package io.gitee.cofenghen.jdbctempleplus.support;


import lombok.Data;
import lombok.SneakyThrows;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

//@Data
//   class FIELD_NAME_Model {
//
//    private Class<?> aClass;
//    private String name;
//
//    public FIELD_NAME_Model(Class<?> aClass, String name) {
//        this.aClass = aClass;
//        this.name = name;
//    }
//}

/**
 * 条件
 */

public class Condition<T> implements Serializable {

    private static final Map<SFunction<?, ?>, String> FIELD_NAME_CACHE = new HashMap<>();
    private   String column=null;

    public Operator getOperator() {
        return operator;
    }

    private   Operator operator;

    public Object getValue() {
        return value;
    }

    private   Object value;
    private SFunction<T, ?> fieldGetter=null;
    private Class<T> entityClass;
    public Condition(SFunction<T, ?> fieldGetter, Operator operator, Object value) {
        this.fieldGetter = fieldGetter;

        this.operator = operator;
        this.value = value;

    }
    public Condition(String column, Operator operator, Object value) {
        this.column = column;
        this.operator = operator;
        this.value = value;
    }
    // 通过反射获取字段名

    // 通过 SerializedLambda 获取字段名
    @SneakyThrows
    public String getFieldName() {

        if (FIELD_NAME_CACHE.containsKey(fieldGetter)) {
            return FIELD_NAME_CACHE.get(fieldGetter);
        }

        Method writeReplace = fieldGetter.getClass().getDeclaredMethod("writeReplace");
        writeReplace.setAccessible(true);
        SerializedLambda serializedLambda = (SerializedLambda) writeReplace.invoke(fieldGetter);
        String methodName = serializedLambda.getImplMethodName();
        String implClass = serializedLambda.getImplClass().replace('/', '.');
        this.entityClass = (Class<T>) Class.forName(implClass);

        String name = null;
        if (methodName.startsWith("get")) {
            name = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);


        }
        //加入缓存


        var meta = EntityParser.parse(entityClass);
        var columnName = meta.getFieldMeta(name).getColumnName();

        FIELD_NAME_CACHE.put(fieldGetter, columnName);

        return columnName;


    }


    public String  getColumn()
    {
        if (fieldGetter!=null)
            this.column=getFieldName();
        return  this.column;
    }



}
